package com.fab.md5;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.lamerman.FileDialog;

public class MD5Checker extends Activity {
    private static final String MY_AD_UNIT_ID = "a14e526cbc1658b"  ;
	/** Called when the activity is first created. */
	
	private Button file1;
	private Button file2;
	private Button check;
	private EditText md5_1,md5_2;
	private CheckBox checkbox;
	private TextView text1,text2,text3,file1txt,file2txt;
	
	private String filePath;
	
	private int FILE1 = 1;
	private int FILE2 = 2;
	private String data;
	private String test;
	private AdView adView;
	private ProgressDialog progressDialog ;
	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("MD5 Checker");
        setContentView(R.layout.main);
        
     // Lookup R.layout.main
        LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout);
          
        // Create the adView
        // Please replace MY_BANNER_UNIT_ID with your AdMob Publisher ID
        AdView adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);
      
        // Add the adView to it
        layout.addView(adView);
         
        // Initiate a generic request to load it with an ad
        AdRequest request = new AdRequest();
        //request.setTesting(true);

        adView.loadAd(request);    
        
        init();
    }
    
    public void init()
    {
    	//retrieve objects per id
    	md5_1 = (EditText)this.findViewById(R.id.md5_1);
    	md5_2 = (EditText)this.findViewById(R.id.md5_2);
    	file1 = (Button)this.findViewById(R.id.file1);
    	file2 = (Button)this.findViewById(R.id.file2);
    	check = (Button)this.findViewById(R.id.check);
    	checkbox = (CheckBox)this.findViewById(R.id.checkbox);
    	text1 = (TextView)this.findViewById(R.id.text1);
    	text2 = (TextView)this.findViewById(R.id.text2);
    	text3 = (TextView)this.findViewById(R.id.text3);
    	file1txt = (TextView)this.findViewById(R.id.file1txt);
    	file2txt = (TextView)this.findViewById(R.id.file2txt);
    	
    	//Initialize progressDialog
    	progressDialog = new ProgressDialog(this);
    	progressDialog.setTitle("Calculating Checksum");
    	progressDialog.setMessage("Please wait, this operation can take several seconds");
    	progressDialog.setIndeterminate(true);
    	
    	//set a listener to the buttons
     // 	bList.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ listRules(); }});
    	file1.setOnClickListener(new Button.OnClickListener() { 
    		public void onClick (View v){ 
    			addFile1();
    			
    			}});
    			
    	
    	
    	file2.setOnClickListener(new Button.OnClickListener() { 
    		public void onClick (View v){ 
    			addFile2();
    			
    			}});
    	
    	check.setOnClickListener(new Button.OnClickListener() { 
    		public void onClick (View v){ 
    			check(); }});
    	
    
    	    	
    	
    	
    }
    
    public void addFile1()
    {
    	
    	Intent intent = new Intent(this.getBaseContext(),FileDialog.class);
    	intent.putExtra(FileDialog.START_PATH, "/");
    	startActivityForResult(intent, FILE1);
    	    	
    }
    
    public void addFile2()
    {
    	
    	Intent intent = new Intent(this.getBaseContext(),FileDialog.class);
    	intent.putExtra(FileDialog.START_PATH, "/");
    	startActivityForResult(intent, FILE2);
   
    	
    	
    }
    
    @Override
    public synchronized void onActivityResult(final int requestCode,
            int resultCode, final Intent data) {

            if (resultCode == Activity.RESULT_OK) {
            	
                filePath = data.getStringExtra(FileDialog.RESULT_PATH);
                if(requestCode == FILE1)
                {
                	file1txt.setText(filePath);
                	progressDialog.show();
                	new Thread(new Runnable(){
					public void run() {
						try {
							String sum = createChecksum(file1txt.getText().toString());
							Message msg = new Message() ;
							 // populates the message
				            msg = handler.obtainMessage(FILE1, (Object) sum);
				 
				            // sends the message to our handler
				            handler.sendMessage(msg);
							
														
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// TODO Auto-generated method stub
						
					}
                	}).start();
                }
                if(requestCode == FILE2)
                {
                	file2txt.setText(filePath);
                	progressDialog.show();
                	new Thread(new Runnable(){
					public void run() {
						try {
							String sum = createChecksum(file2txt.getText().toString());
							Message msg = new Message() ;
							 // populates the message
				            msg = handler.obtainMessage(FILE2, (Object) sum);
				 
				            // sends the message to our handler
				            handler.sendMessage(msg);
							
											
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// TODO Auto-generated method stub
						
					}
                	}).start();
                }

            } else if (resultCode == Activity.RESULT_CANCELED) {
            	Toast.makeText(this, "No file has been selected", 5).show();
   	            }

    }
    
    public void check(){
    	
    	if (md5_1.getText() != null || md5_2.getText() != null)
    	{
    		if(md5_1.getText().toString().equalsIgnoreCase(md5_2.getText().toString()))
    		{
    			checkbox.setText("Checksums are identical");
    		checkbox.setChecked(true);
    		}
    		else {
    			checkbox.setText("Checksums are different");
    			checkbox.setChecked(false);
    		}
    		
    	}
    	
    }
    
    public String createChecksum(String filename) throws Exception
    {
    	InputStream fis =  new FileInputStream(filename);

    	byte[] buffer = new byte[1024];
    	MessageDigest complete = MessageDigest.getInstance("MD5");
    	int numRead;
    	do {
    		numRead = fis.read(buffer);
    		if (numRead > 0) {
    			complete.update(buffer, 0, numRead);
    		}
    	} while (numRead != -1);
    	fis.close();
    	
    	
    	return getHexString(complete.digest());
    }
    
    public static String getHexString(byte[] b) {
		  String result = "";
		  for (int i=0; i < b.length; i++) {
		    result +=
		          Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
		  }
		  return result;
		}
	  
   
    
    private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
				case 1:
					md5_1.setText(msg.obj.toString());
				break;
				case 2:
					md5_2.setText(msg.obj.toString());
				break;
				default:
				break;
			}

		}
	};
    
    
}